package demo.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import demo.common.exception.SnowException;
import demo.common.exception.SnowExceptionEnum;
import demo.common.utils.BeanHelper;
import demo.user.dto.UserDTO;
import demo.user.mapper.UserMapper;
import demo.user.pojo.User;
import demo.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LonelySnow
 * @since 2020-06-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

//    // 密码有关
//    @Autowired
//    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 增加一条
     * @param userDTO
     */
    @Override
    @Transactional
    public boolean addOne(UserDTO userDTO) {
        User user = BeanHelper.copyProperties(userDTO, User.class);
        boolean result = this.save(user);
        return result;
    }

    /**
     * 修改一条
     * @param userDTO
     * @param id
     * @return
     */
    @Override
    @Transactional
    public boolean updateOne(UserDTO userDTO, Long id) {
        User user = BeanHelper.copyProperties(userDTO, User.class);
        user.setId(id);
        boolean result = this.updateById(user);
        return result;
    }

    /**
     * 删除一条
     * @param id
     */
    @Override
    public void deleteOne(Long id) {
        this.removeById(id);
    }

    /**
     * 查询全部
     * @return
     */
    @Override
    public List<UserDTO> selectAll() {
        List<User> userList = this.list();
        List<UserDTO> result = BeanHelper.copyWithCollection(userList, UserDTO.class);
        return result;
    }

    /**
     * 查询一条
     * @param id
     * @return
     */
    @Override
    public UserDTO selectOne(Long id) {
        User user = this.getById(id);
        UserDTO userDTO = BeanHelper.copyProperties(user, UserDTO.class);
        return userDTO;
    }

    /**
     * 根据用户名密码查询一条数据
     * @param userName
     * @return
     */
    @Override
    public UserDTO userLogin(String userName, String password) {
        QueryWrapper<User> where = new QueryWrapper<>();
        where.lambda().eq(User::getUsername, userName);
        User user = this.getOne(where);
        // 判断用户是否为空
        if (user == null) {
            throw new SnowException(SnowExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        // 校验密码是否正确
        if (! user.getPassword().equals(password)) {
            throw new SnowException(SnowExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        UserDTO result = BeanHelper.copyProperties(user, UserDTO.class);
        return result;
    }
}
